<script setup>
  import PageLayout from '@/components/PageLayout.vue'
  import GridTemplate from '@/components/GridTemplate.vue'
  import InfoCard from '@/components/InfoCard.vue'
  import { getRoomList, getSeatDetail, reservation } from '@/api'
  import { useRouter, useRoute } from 'vue-router'
  import { onMounted, ref, computed } from 'vue'
  import { ElMessage } from 'element-plus'
  import { ElMessageBox } from 'element-plus'

  const router = useRouter()
  const roomList = ref([])
  const route = useRoute()
  const libraryId = Number(route.params.id)
  const roomData = ref({})
  const infoCardCollapse = ref(true)
  const loading = ref(false)
  const submitLoading = ref(false)

  // 预约座位
  const dialogVisible = ref(false)
  const currentSeat = ref({})
  const timeRange = ref([8, 20])
  const seatId = ref(0)
  const marks = {}
  for (let i = 0; i <= 28; i++) {
    const hour = 8 + Math.floor(i / 2)
    const min = (i % 2) * 30
    // 只在整点显示标签（8:00、9:00...）
    if (min === 0) marks[i] = `${hour}:00`
    else marks[i] = '' // 非整点留空，避免太密
  }
  const formatTip = val => {
    const totalMin = 8 * 60 + val * 30
    const h = Math.floor(totalMin / 60)
    const m = totalMin % 60
    return `${h.toString().padStart(2, '0')}:${m.toString().padStart(2, '0')}`
  }

  const statusMap = ['关闭', '开放', '维修']
  const TypeMap = ['教室', '自习室']

  const showInfoData = computed(() => {
    if (infoCardCollapse.value) return { title: ['房间:', roomData.value.name] }
    return {
      title: ['房间:', roomData.value.name],
      content: [
        [
          ['Id', roomData.value.id],
          ['所属图书馆', roomData.value.libraryId],
        ],
        [
          ['房间类型', roomData.value.typeName],
          ['状态', roomData.value.statusName],
        ],
        [
          ['容量', roomData.value.capacity],
          ['设备配置', roomData.value.equipmentConfig],
          ['设施配置', roomData.value.facilityConfig],
        ],
      ],
    }
  })

  const showGridOptions = computed(() => {
    return roomData.value.map ?? {}
  })

  const onBack = () => {
    router.back()
  }

  const onClickRoom = room => {
    roomData.value = room
  }

  const onClickCollapse = () => {
    infoCardCollapse.value = !infoCardCollapse.value
  }

  const onClickGridItem = item => {
    console.log(item.id)
    if (item.type !== 2) return
    dialogVisible.value = true
    seatId.value = item.id
    submitLoading.value = false
    getSeatDetail(item.id).then(res => {
      currentSeat.value = res.data
    })
  }

  function indexToTime(idx) {
    const totalMinutes = 8 * 60 + idx * 30 // 从 8:00 开始，每格 30 min
    const h = Math.floor(totalMinutes / 60)
    const m = totalMinutes % 60
    return `${h.toString().padStart(2, '0')}:${m.toString().padStart(2, '0')}`
  }

  const onConfirm = () => {
    const max = Math.max(...timeRange.value)
    const min = Math.min(...timeRange.value)
    const startTime = `${indexToTime(min)}:00`
    const endTime = `${indexToTime(max)}:00`

    console.log(startTime, endTime)
    const data = { seatId: seatId.value, startTime, endTime }

    submitLoading.value = true
    reservation(data)
      .then(() => {
        ElMessage.success('预约成功')
        dialogVisible.value = false
        submitLoading.value = false
      })
      .finally(() => (submitLoading.value = false))
  }

  const handleGetRoomList = () => {
    loading.value = true
    return getRoomList({ libraryId })
      .then(res => {
        roomList.value = res.data
          .filter(item => item.roomStatus === 1 && item.roomType === 1)
          .map(item => ({
            ...item,
            statusName: statusMap[item.roomStatus],
            typeName: TypeMap[item.roomType],
            map: item.map ? JSON.parse(item.map) : { height: 15, width: 20, data: [] },
          }))
      })
      .finally(() => {
        loading.value = false
      })
  }

  onMounted(() => {
    handleGetRoomList().then(() => {
      roomData.value = roomList.value[0]
    })
  })
</script>

<template>
  <page-layout>
    <template #header>
      <el-button @click="onBack">返回</el-button>
      <el-button @click="handleGetRoomList">刷新</el-button>
    </template>

    <div class="wrapper" v-loading="loading">
      <div class="flex-col">
        <div class="title">房间列表</div>
        <div class="room-list flex-col">
          <el-button v-for="room in roomList" :key="room.id" class="room-item shadow" @click="onClickRoom(room)">
            <span class="room-content">
              <span>{{ room.name }}</span>
              <el-tag effect="dark">{{ room.typeName }}</el-tag>
              <el-tag type="warning" effect="dark" v-if="room.roomStatus === 2">{{ room.statusName }}</el-tag>
            </span>
          </el-button>
        </div>
      </div>
      <div class="flex-1 flex-col">
        <div class="card-wrapper">
          <info-card :data="showInfoData" />
          <el-button class="collapse-btn" @click="onClickCollapse">展开/收起</el-button>
        </div>
        <grid-template ref="grid" :readonly="true" :options="showGridOptions" @click-item="onClickGridItem">
        </grid-template>
      </div>
    </div>

    <el-dialog v-model="dialogVisible" title="预约座位" width="500px" append-to-body>
      <div>
        <div class="label">已预约时间段</div>
        <div v-for="item in currentSeat" :key="item.reservationId">
          <div>{{ item.startTime }} - {{ item.endTime }}</div>
        </div>
        <div class="label">请选择预约时间段</div>
        <el-slider v-model="timeRange" range show-stops :min="0" :max="28" :format-tooltip="formatTip" />
      </div>
      <template #footer>
        <el-button type="primary" @click="onConfirm" :loading="submitLoading">确认</el-button>
      </template>
    </el-dialog>
  </page-layout>
</template>

<style scoped>
  .wrapper {
    display: flex;
    height: 100%;
    gap: var(--padding-2);
  }

  .title {
    text-align: center;
    position: sticky;
    top: 0;
    font-size: 28px;
    color: var(--primary-500);
    padding-bottom: 20px;
  }

  .room-list {
    width: 300px;
    gap: 16px;
    height: 100%;
    overflow-y: auto;
  }

  .room-item {
    padding: 30px;
    margin-left: 0;
  }

  .room-content {
    width: 100px;
    font-size: 20px;
    font-weight: 600;
    color: var(--primary-500);
    display: flex;
    gap: 20px;
    justify-content: center;
  }

  .card-wrapper {
    position: relative;
  }

  .collapse-btn {
    position: absolute;
    bottom: 20px;
    right: 20px;
  }

  .label {
    font-weight: bold;
    color: var(--primary-500);
    margin-block: 10px;
  }
</style>
